//
//  EventViewerViewController.m
//  SecretRoom
//
//  Created by Sitdhibhong Laokok on 9/3/54 BE.
//  Copyright 2554 App Tree. All rights reserved.
//

#import "EventViewerViewController.h"

#import "EventDetailsViewerViewController.h"
#import "EvidenceOfEventViewerViewController.h"

#import "Event.h"

@interface EventViewerViewController ()
- (void)performSyncEventInBackground;
@end

@implementation EventViewerViewController

@synthesize currentEventDisplay=_currentEventDisplay;
@synthesize eventFetchedController=_eventFetchedController;
@synthesize context;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithManagedObjectContext:(NSManagedObjectContext *)cx
{
    if (self = [super initWithStyle:UITableViewStyleGrouped]) {
        self.context = cx;
    }
    
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIBarButtonItem *addEvent = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addNewEventButtonClicked)];
    
    UIBarButtonItem *flexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
    UIBarButtonItem *eventsOptions = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(eventAction)];
    
    self.navigationController.toolbarHidden = NO;
    
    self.toolbarItems = [NSArray arrayWithObjects:addEvent, flexible, nil];
    
    [addEvent release];
    [flexible release];
    [eventsOptions release];
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    NSLog(@"View vill appear");
    NSError *error = nil;
    [self.eventFetchedController performFetch:&error];
    if (error != nil) {
        NSLog(@"Error: %@", [error localizedDescription]);
    }
    
    [self.tableView reloadData];
    
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    self.navigationController.toolbar.barStyle = UIBarStyleDefault;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[[self.eventFetchedController sections] lastObject] numberOfObjects];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    }
    
    Event *event = [self.eventFetchedController objectAtIndexPath:indexPath];
    
    cell.textLabel.text = event.eventName;
    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{   
    EvidenceOfEventViewerViewController *evidencesOfEvent = [[[EvidenceOfEventViewerViewController alloc] initWithNibName:@"EvidenceOfEventViewerViewController" bundle:nil] autorelease];
    
    evidencesOfEvent.context = self.context;
    evidencesOfEvent.event = [self.eventFetchedController objectAtIndexPath:indexPath];
    
    [self.navigationController pushViewController:evidencesOfEvent animated:YES];
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    EventDetailsViewerViewController *eventDetailViewer = [[EventDetailsViewerViewController alloc] initWithNibName:@"EventDetailsViewerViewController" bundle:nil];
    
    eventDetailViewer.context = self.context;
    eventDetailViewer.eventForDetailsDisplayInformation = [self.eventFetchedController objectAtIndexPath:indexPath];
    
    NSLog(@"Event information : %@", eventDetailViewer.eventForDetailsDisplayInformation.eventName);
    
    [self.navigationController pushViewController:eventDetailViewer animated:YES];
    
    [eventDetailViewer release];
}

#pragma mark - Swipe to Delete
// For delete cell at indexPath
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        Event *deleteEvent = [self.eventFetchedController objectAtIndexPath:indexPath];
        
        if (self.currentEventDisplay == kSREventCategoryLogBook) {
            NSLog(@"indexPath: %@", indexPath);
            
            
            [[[SRConnectionControlCenter sharedInstance] manageObjectContext] deleteObject:deleteEvent];
            
            [self.tableView reloadData];
            
        } else {
            deleteEvent.isArchived = [NSNumber numberWithBool:YES];
        }
        
        NSError *error = nil;
        [[[SRConnectionControlCenter sharedInstance] manageObjectContext] save:&error];
        if (error != nil) {
            NSLog(@"%s Error while saving deleted row entity: %@", __PRETTY_FUNCTION__, [error localizedDescription]);
        }
    }
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.currentEventDisplay == kSREventCategoryLogBook) {
        return @"Delete";
    } else {
        return @"Archive";
    }
}

#pragma mark - Custom method
- (void)addNewEventButtonClicked
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"addNewEvent" object:nil];
    [self.eventFetchedController performFetch:nil];
    [self.tableView reloadData];
}

#pragma mark - NSFetchedResultsControllerDelegate
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
//    [self.tableView beginUpdates];
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
//    [self.tableView endUpdates];
    [self.tableView reloadData];
}

#pragma mark - Accessor Override
- (void)setCurrentEventDisplay:(kSREventCategory)ced
{
    _currentEventDisplay = ced;
    self.title = [SRConnectionControlCenter categoryStringWithCategory:ced];
    
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = [NSEntityDescription entityForName:@"Event" inManagedObjectContext:self.context];
    NSSortDescriptor *dateSortor = [[NSSortDescriptor alloc] initWithKey:@"eventTimestamp" ascending:NO];
    
    request.sortDescriptors = [NSArray arrayWithObjects:dateSortor, nil];
    [dateSortor release];
    
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    gregorian.locale = [NSLocale systemLocale];
    NSDateComponents *yearMonthDayComponents = [gregorian components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:[SLCommonsDateUtility currentGMTDate]];
    NSDateComponents *yearMonthNextDayComponents = [yearMonthDayComponents copy];
    yearMonthNextDayComponents.day++;
    
    switch (self.currentEventDisplay) {
        case kSREventCategoryInbox:
            request.predicate = [NSPredicate predicateWithFormat:@"eventTimestamp = nil AND isArchived = %@", [NSNumber numberWithBool:NO]];
            break;
            
        case kSREventCategoryOverDue:
            request.predicate = [NSPredicate predicateWithFormat:@"eventTimestamp < %@ AND isArchived = %@", [gregorian dateFromComponents:yearMonthDayComponents], [NSNumber numberWithBool:NO]];
            break; 
            
        case kSREventCategoryToday:
            request.predicate = [NSPredicate predicateWithFormat:@"eventTimestamp >= %@ AND eventTimestamp <= %@ AND isArchived = %@", [gregorian dateFromComponents:yearMonthDayComponents], [gregorian dateFromComponents:yearMonthNextDayComponents], [NSNumber numberWithBool:NO]];
            break;
            
        case kSREventCategoryLogBook:
            request.predicate = [NSPredicate predicateWithFormat:@"isArchived = %@", [NSNumber numberWithBool:YES]];
            break;
            
        case kSREventCategorySchedule:
            yearMonthDayComponents.day += 1;
            request.predicate = [NSPredicate predicateWithFormat:@"eventTimestamp >= %@ AND isArchived = %@", [gregorian dateFromComponents:yearMonthDayComponents], [NSNumber numberWithBool:NO]];
            break;
            
        default:
            break;
    }
    
    NSLog(@"Predicate: %@", request.predicate);
    
    NSFetchedResultsController *fetchRequestController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.context sectionNameKeyPath:nil cacheName:nil];
    fetchRequestController.delegate = self;
    
    [gregorian release];
    [request release];
    [yearMonthNextDayComponents release];
    
    self.eventFetchedController = fetchRequestController;
    [fetchRequestController release];
}

- (void)eventAction
{
    UIActionSheet *eventSyncedOptions = [[UIActionSheet alloc] initWithTitle:@"Event Options" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Start Sync" otherButtonTitles:nil];
    [eventSyncedOptions showFromToolbar:self.navigationController.toolbar];
    [eventSyncedOptions release];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != actionSheet.cancelButtonIndex) {
        // Start synced
        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Start Event Sync" message:@"You can not add a new event while syncing. Do you want to sync ?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Start Sync", nil];
        
        [message show];
        [message release];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.cancelButtonIndex != buttonIndex) {
        [NSThread detachNewThreadSelector:@selector(performSyncEventInBackground) toTarget:self withObject:nil];
    }
}

- (void) performSyncEventInBackground
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    for (int i = 0; i < 10000; i++) {
        NSLog(@"i = %i", i);
    }
    [pool release];
}

@end
